import 'dart:js_interop';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

class DioDemo extends StatelessWidget {
  const DioDemo({
    super.key,
    this.title = '',
    this.content = '',
    this.tColor = Colors.orange,
    this.cColor = Colors.yellow,
  });

  final String title;
  final String content;
  final Color tColor;
  final Color cColor;

  // 重写build 返回需要封装的组件即可
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.purple,
          title: Center(
            child: Text(
              '标题为:$title',
              style: TextStyle(
                  color: tColor, fontSize: 30, fontWeight: FontWeight.w900),
            ),
          ),
        ),
        body: const Center(
          child: MyStateWidget(),
        ),
      ),
    );
  }
}

class MyStateWidget extends StatefulWidget {
  const MyStateWidget({super.key});

  @override
  // 创建组件时调用
  State<MyStateWidget> createState() {
    return _MyStateWidgetState();
  }
}

// 1. 默认笑话，初始化获取数据，渲染到页面
class _MyStateWidgetState extends State<MyStateWidget> {
  final dio = Dio();
  List goodsList = [];

  // 定义笑话状态变量
  String joke = '狐狸很容易摔跤，因为脚滑';
  @override
  // 组件被初始化时调用
  void initState() {
    super.initState();
    loadData();
  }

  loadData() async {
    final res =
        await dio.get<String>('https://api-vue-base.itheima.net/api/joke');
    // ignore: avoid_print
    // print(res);
    setState(() {
      joke = res.toString();
    });

    // 商品列表接口
    final goods = await dio.get('https://mock.boxuegu.com/mock/1172/orders');
    print(goods.data);
    setState(() {
      goodsList = goods.data;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text(
          '$joke',
          style: TextStyle(fontSize: 30, fontWeight: FontWeight.w900),
        ),
        ElevatedButton(
          onPressed: () {
            loadData();
          },
          child: const Text('换一条'),
        )
      ],
    );
  }
}
